from fastapi import APIRouter, Request
from pydantic import BaseModel
from config.database_connect import get_db_connection


class CheckLogin(BaseModel):
    username: str
    password: str


appLogin = APIRouter()


@appLogin.post("/api/login")
async def login(check: CheckLogin, request: Request):
    db = get_db_connection()
    if not db: return {"status": "error", "message": "数据库连接失败"}
    with db.cursor() as cursor:
        # 此处预留sql注入漏洞用于渗透测试,账号admin
        sql = f"SELECT id, username FROM users WHERE username='{check.username}' AND password='{check.password}'"
        cursor.execute(sql)  # 直接执行字符串
        user = cursor.fetchone()

    db.close()
    if user:
        # 将用户ID存储到session中
        request.session['user_id'] = user['id']
        request.session['username'] = user['username']

        return {
            "status": "success",
            "user_id": user['id'],
            "username": user['username'],
            "message": "flag{666}"
        }
    else:
        return {"status": "error", "message": "用户名或密码错误"}